package com.tianheng.wanzhou.datacollecting.netty.zhengjing.client;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tianheng.wanzhou.datacollecting.db.entity.MachineList;
import com.tianheng.wanzhou.datacollecting.db.service.IHuafangZhengjingService;
import com.tianheng.wanzhou.datacollecting.db.service.IKaiyuanZhengjingService;
import com.tianheng.wanzhou.datacollecting.db.service.IMachineListService;
import com.tianheng.wanzhou.datacollecting.netty.zhengjing.receiver.Receiver;
import com.tianheng.wanzhou.datacollecting.netty.zhengjing.receiver.ReceiverFactory;
import com.tianheng.wanzhou.datacollecting.util.SerializeUtil;
import com.tianheng.wanzhou.datacollecting.util.StrUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: yujw
 * @Date: 2020/5/12 14:26
 * @Version 1.0
 */
@Slf4j
@Component(value = "r200Handler")
@Scope("prototype")
public class ClientHandler extends ChannelInboundHandlerAdapter {

    @Autowired
    IHuafangZhengjingService huafangZhengjingService;

    @Autowired
    IKaiyuanZhengjingService kaiyuanZhengjingService;

    @Autowired
    ReceiverFactory receiverFactory;

//    @Resource
//    Jedis jedis;
@Autowired
IMachineListService machineListService;
    private List<MachineList> machineList = new ArrayList<>();

    private static ClientHandler clientHandler;

    @PostConstruct
    public void init() {
        clientHandler = this;
        huafangZhengjingService = this.huafangZhengjingService;
        kaiyuanZhengjingService = this.kaiyuanZhengjingService;
//        jedis = this.jedis;
        QueryWrapper<MachineList> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mac_type", 0).eq("status", 1);
        machineList = machineListService.list(queryWrapper);
        receiverFactory = this.receiverFactory;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIP = insocket.getAddress().getHostAddress();
        log.info("连接服务端" + clientIP + "成功!");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIP = insocket.getAddress().getHostAddress();
        try {
            MachineList machine = new MachineList();
            for (MachineList machine1 : this.machineList) {
                if(clientIP.equals(machine1.getMacIp())){
                    machine =machine1;
                    break;
                }
            }
            ByteBuf buf = (ByteBuf)msg;
            byte[] bytes = new byte[buf.readableBytes()];
            buf.readBytes(bytes);
            String str = StrUtil.bytesToHexString(bytes);
            log.info("收到数据:" + str);
            Receiver receiver = receiverFactory.getReceiver(machine.getSonType());
            receiver.save(str.substring(18), machine.getMacIp(), machine.getCompany(), machine.getWorkshop(), machine.getMacId());
        }finally {
            ReferenceCountUtil.release(msg);
        }
        ctx.channel().close();
        ctx.close();
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        log.info("数据读取完毕");
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIP = insocket.getAddress().getHostAddress();
        log.info("连接"+ clientIP +"移除");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("发生错误:" + cause.toString());
        ctx.close();
    }

}
